#include <avr/io.h>
//#include <avr/delay.h>

//#include "my_bit.h"
//#include "my_types.h"

//300 ~ 3s 
//100 ~ 1s

#define CHANNELS 4
#define CPUHZ 400
unsigned char chA[CHANNELS];
unsigned char tmpOut;
unsigned char oldChA[CHANNELS];
double timeA[CHANNELS];
int elapsedCyclesA[CHANNELS];
int elapsedTimeA[CHANNELS]; //in microseconds

int parseToUs(int cycles)
{
	int tUs = cycles*10/CPUHZ;
	return tUs;
}	

void parse(int channel)
{
	
	// sjekk om bit er lav
	if(chA[channel]==0)
	{
		// regn ut tid siden sist
		elapsedCyclesA[channel] = TCNT1-timeA[channel];
		elapsedTimeA[channel] = parseToUs(elapsedCyclesA[channel]);
		
	}
	else
	{
		// set start tid
		timeA[channel]=TCNT1;
		// TCNT1
	}
	oldChA[channel] = chA[channel];
	//PORTC = chA[channel];
}


int main(void)
{
	unsigned char counter;
	//unsigned char ch0,ch1,ch2,ch3;
	
	int n = 0;
	DDRA = 0x00; // PORTA = INPUT
	DDRB = 0xFF; // PORTB = OUTPUT
	DDRC = 0xFF; // PORTC = OUTPUT / DEBUG

	// INIT
	n=0;
	while(n<CHANNELS)
	{
		chA[n]=0;
		oldChA[n]=0;
		elapsedCyclesA[n]=0;
		n++;
	}
	TCCR1B |= (1 << CS10); // Set up timer 

	
	while(1)
	{

		// READ Channel 0
		//chA[0] = PORTA & (1<<7);		
		// READ Channel 1
		//chA[1] = PORTA & (1<<6);
		// READ Channel 2
		//chA[2] = PORTA & (1<<5);
		// READ Channel 3
		//chA[3] = PORTA & (1<<4);

		// READ ALL CHANNELS
		n=0;
		int bits = 7;
		while(n<CHANNELS)
		{
			chA[n]= PORTA & (1<<(bits-n));
			// COMPARE channel to OLDCHANNEL
			if(chA[n]!=oldChA[n])
			{
				parse(n);
				oldChA[n] = chA[n];
			}
			n++;
		}



		// output all bits on PORTB
		tmpOut = ((chA[0] | chA[1]) | (chA[2] | chA[3]));
		PORTC = tmpOut;
	}
	return 1;
}

